package top.jojoace.JWT;

import com.alibaba.fastjson2.JSON;
import com.google.common.collect.ImmutableMap;
import com.nimbusds.jose.*;
import com.nimbusds.jose.crypto.MACSigner;
import com.nimbusds.jose.crypto.MACVerifier;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.Test;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

public class JWTUtil {


    /**
     * JWS
     * 使用HMAC SHA-256 进行加密 与 解密
     * 基于相同的 secret (对称算法)
     * <p/>
     * 算法     Secret长度
     * HS256   32
     * HS384   64
     * HS512   64
     *
     * <h2>JWT 结构</h2>
     * heard.payload.signature
     * 头。负载。签名
     *
     * 头（base64 转码）：{
     *     type：”JWT“
     *     alg：”HS256“ //定义加密方式
     * }
     *负载（base64 转码）：传递的内容
     * 签名：用heard的alg加密方式，配合密钥加密进行加密
     * signature = HS256（ 密钥，heard , payload )
     *
     *
     * @throws Exception
     */
    @Test
    public void jwsTest() throws Exception {

        //密钥
        //String sharedSecret = "密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥密钥";
        String sharedSecret = RandomStringUtils.random(64,true,true);
        JWSSigner jwsSigner = new MACSigner(sharedSecret);
        System.out.println("密钥:"+ sharedSecret);

        //头
        JWSHeader header = new JWSHeader(JWSAlgorithm.HS256);
        //JWSHeader header = new JWSHeader(JWSAlgorithm.HS384);
        //JWSHeader header = new JWSHeader(JWSAlgorithm.HS512);

        //负载
        Payload payload = new Payload(ImmutableMap.of("name","admin","password","123456"));
        JWSObject jwsObject = new JWSObject(header, payload);

        //签名内容
        jwsObject.sign(jwsSigner);

        //获取 idToken
        final String idToken = jwsObject.serialize();
        System.out.println("id_token: " + idToken);

        //解析JWT
        final JWSObject parseJWS = JWSObject.parse(idToken);

        //拿到负载
        Map<String, Object> decryptPayload = parseJWS.getPayload().toJSONObject();
        System.out.println(idToken + " -> "+ decryptPayload.toString());

        //验证密钥
        final boolean verify = parseJWS.verify(new MACVerifier(sharedSecret));//true
        final boolean verify_1 = parseJWS.verify(new MACVerifier(sharedSecret+"假密钥"));//false

    }


}
